#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
    /* #include <arpa/inet.h>
        uni32_t htonl(uni32_t hostlong); // host to net long int
        uni16_t htonl(uni16_t hostshort); // host to net short int
        uni32_t ntohl(uni32_t netlong); // net to host long int
        uni16_t ntohl(uni16_t netshort); // net to host short int
        unsigned long inet_addr(const char* cp); // cp e.g., "192.168.10.130"
        char* inet_ntoa(struct in_addr in);
    */

int main(void)
{
    unsigned short port = 0;
    int sockfd, ret, ret_val = 1;
    struct sockaddr_in myaddr;
    socklen_t addr_len;
    char ip_name_str[INET_ADDRSTRLEN];

    sockfd = socket(AF_INET, SOCK_STREAM, 0); /* AF_INET: ipv4 */
    if(sockfd == -1) {
        perror("socket()");
        return EXIT_FAILURE;
    }

    myaddr.sin_family = AF_INET; /* ipv4 */
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY); /* INADDR_ANY: 0 */
    myaddr.sin_port = 0; /* if .sin_port is set to 0, a free port number allocated by bind() */
    addr_len = sizeof(myaddr);
    ret = bind(sockfd, (struct sockaddr *)&myaddr, addr_len);
        /* bind() not return the port number to myaddr: bind(int, const struct sockaddr, socklen_t)
           use getsockname() to get the allocated port number */
    if(ret == 0) {
        addr_len = sizeof(myaddr);
        ret = getsockname(sockfd, (struct sockaddr *)&myaddr, &addr_len);
        if(ret == 0) {
            port = ntohs(myaddr.sin_port);
            printf("port number = %d\n", port);
            strcpy(ip_name_str, inet_ntoa(myaddr.sin_addr));
            printf("host addr = %s\n", ip_name_str);
        } else {
            ret_val = 0;
        }
    } else {
        ret_val = 0;
    }

    ret = close(sockfd); /* close() defined in <unistd.h> */
    if(ret != 0) {
        ret_val = 0;
    }

    return ret_val;
}


